<template>
  <div class="placeOrder">
    <!-- 地址 -->
    <el-card class="box-card">
      <div class="flex_ listItem">
        <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.send + ')'"></div>
        <div
          class="flex_1 content"
          @click="openAddressDrawer('0')"
          v-if="!send_address.name && position_address.name == ''"
        >选择发货地址</div>
        <div
          class="flex_1 content"
          @click="openAddressDrawer('0')"
          v-else
        >{{ send_address.name ? send_address.name : position_address.name }}</div>
      </div>
      <div class="flex_ listItem">
        <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.get + ')'"></div>
        <div
          class="flex_1 content"
          @click="openAddressDrawer('1')"
        >{{ put_address.name ? put_address.name : '选择收货地址' }}</div>
      </div>
    </el-card>
    <!--   估算距离 预计骑行时间   -->
    <div v-show="firstTotalPrice !== 0" class="estimate-order flex_cc">
      <i class="el-icon-bicycle"></i>
      <div>配送距离 {{ distance }} 公里，预计骑手骑行时间为 {{ totalTime }}</div>
    </div>
    <!-- 货物 -->
    <el-card class="box-card">
      <div class="flex_ listItem">
        <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.goods + ')'"></div>
        <div class="content">物品信息</div>
        <div class="rightLink" @click="openGoodsDialog()">
          <span>{{ confirmGoods }}</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="flex_ listItem">
        <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.time + ')'"></div>
        <div class="content">发货时间</div>
        <div class="rightLink" @click="clickChooseTime()">
          <span>{{ confirmTime }}</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="flex_ listItem" @click="openCouponsList()">
        <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.coupon + ')'"></div>
        <div class="content">优惠金额</div>
        <div class="rightLink">
          <span v-if="choose_coupon_list !== 'null'">
            已选择 {{ choose_coupon_name }}
          </span>
          <span v-else>请先完善订单信息</span>
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
    </el-card>
    <!-- 备注 -->
    <el-card class="box-card">
      <div class="flex_ listItem">
        <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.note + ')'"></div>
        <div class="content">订单备注</div>
        <div class="rightLink" @click="openOrderDetailDialog()">
          {{ orderDetail === '' ? '备注您的需求' : orderDetail }}
          <i class="el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="flex_ listItem">
        <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.heat + ')'"></div>
        <div class="content">保温箱配送</div>
        <div class="rightLink">
          <el-switch v-model="heat" active-color="#13ce66" inactive-color="#ccc"></el-switch>
        </div>
      </div>
    </el-card>
    <!-- 提示 -->
    <div class="tips">温馨提示：根据相关法律要求</div>
    <!-- 下单 -->
    <div class="flex_ button placeOrderButton">
      <div class="price startingPrice" v-show="firstTotalPrice === 0">起步价：{{ start_price }}元</div>
      <div class="price totalPrice" v-show="firstTotalPrice !== 0">
        费用：{{ finalTotalPrice }}元
        <i class="el-icon-caret-top"></i>
      </div>
      <div class="flex_1 link" @click="submit()">立即下单</div>
    </div>
    <!-- 物品规格 -->
    <van-popup
      v-model="goodsDialog"
      position="bottom"
      :close-on-click-overlay="false"
      :style="{ height: '80%' }"
    >
      <div class="demo-drawer__content">
        <el-form :model="form">
          <div class="flex_cc buttonBox">
            <div class="flex_1 title">选择物品规格</div>
            <el-button type="success" @click="goodsDialogConfirm()">确定</el-button>
          </div>
          <div class="drawer__content_title">物品类型</div>
          <el-radio-group v-model="form.radio1">
            <el-radio-button
              v-for="(item, index) in gives"
              :key="index"
              :label="index"
            >{{ item.name }}</el-radio-button>
          </el-radio-group>
          <div class="drawer__content_title">物品价值</div>
          <el-radio-group v-model="form.radio2" @change="chooseGoodsPrice">
            <el-radio-button
              v-for="(item, index) in goodsPrice"
              :key="index"
              :label="index"
            >{{ item.name }}</el-radio-button>
          </el-radio-group>
          <div class="drawer__content_title">保价服务</div>
          <div class="keepPriceItem">
            <div v-if="keepPriceNumber === 0" class="tips">请先选择物品价值</div>
            <el-checkbox
              v-else-if="keepPriceNumber === 3"
              v-model="buyKeepPrice"
              @change="cancelBuyKeepPrice()"
            >投保3元</el-checkbox>
            <el-checkbox v-else v-model="buyKeepPrice" @change="cancelBuyKeepPrice()">投保5元</el-checkbox>
          </div>
          <div class="flex_ keepPriceItem">
            <el-checkbox v-model="keepPrice">已阅读并同意</el-checkbox>
            <div class="link">《保价协议》</div>
          </div>
        </el-form>
      </div>
    </van-popup>
    <!-- 时间选择器 -->
    <el-drawer
      :with-header="false"
      :visible.sync="datetimeDialog"
      direction="btt"
      size="50%"
      custom-class="demo-drawer"
      ref="drawer"
      :wrapperClosable="false"
    >
      <van-picker
        :columns="dataTime"
        :show-toolbar="true"
        title="选择发货时间"
        @cancel="pickerCancel"
        @confirm="pickerConfirm"
      />
    </el-drawer>
    <!-- 订单备注 -->
    <el-drawer
      :with-header="false"
      :visible.sync="orderDetailDialog"
      direction="btt"
      size="30%"
      custom-class="demo-drawer"
      ref="drawer"
      :wrapperClosable="false"
    >
      <div class="demo-drawer__content">
        <el-form :model="form">
          <div class="flex_cc buttonBox">
            <!-- <el-button type="info" @click="goodsDetailDialogCancel()">取消</el-button> -->
            <div class="flex_1 title">备注您的需求</div>
            <el-button type="success" @click="goodsDetailDialogConfirm()">确定</el-button>
          </div>
          <el-input type="textarea" :rows="4" v-model="orderDetail" placeholder="请输入内容"></el-input>
        </el-form>
      </div>
    </el-drawer>
    <!-- 详细地址 -->
    <el-drawer
      :with-header="false"
      :visible.sync="addressDrawer"
      direction="btt"
      size="60%"
      custom-class="demo-drawer"
      ref="drawer"
      :wrapperClosable="false"
    >
      <el-card>
        <div class="flex_ listItem" @click="openMapDrawer()">
          <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.time + ')'"></div>
          <div class="content">
            <slot v-if="addressType == '0'">
              <div v-if="!send_address.name && position_address.name == '' ">定位失败，请手动选址</div>
              <div v-else-if="send_address.name">{{ send_address.name }}</div>
              <div v-else>{{ position_address.name }}</div>
            </slot>
            <slot v-else-if="addressType == '1'">
              <div v-if="!put_address.name">请选择收货选址</div>
              <div>{{ put_address.name }}</div>
            </slot>
          </div>
          <div class="rightLink">
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="flex_ listItem">
          <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.time + ')'"></div>
          <div class="flex_1 content">
            <van-field
              type="input"
              :clearable="true"
              v-model="send_detail_address"
              placeholder="请补充具体楼层门牌号"
              v-if="addressType == '0'"
            ></van-field>
            <van-field
              type="input"
              :clearable="true"
              v-model="put_detail_address"
              placeholder="请补充具体楼层门牌号"
              v-if="addressType == '1'"
            ></van-field>
          </div>
        </div>
        <div class="flex_ listItem">
          <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.time + ')'"></div>
          <div class="flex_1 content">
            <van-field
              type="input"
              :clearable="true"
              v-model="send_user_tel"
              placeholder="发货人手机号码（必填）"
              v-if="addressType == '0'"
            ></van-field>
            <van-field
              type="input"
              :clearable="true"
              v-model="put_user_tel"
              placeholder="收货人手机号码（必填）"
              v-if="addressType == '1'"
            ></van-field>
          </div>
        </div>
        <div class="flex_ listItem">
          <div class="backgroundImageBase icon" :style="'background-image: url(' + icon.time + ')'"></div>
          <div class="flex_1 content">
            <van-field
              type="input"
              :clearable="true"
              v-model="send_user_name"
              placeholder="联系人姓名"
              v-if="addressType == '0'"
            ></van-field>
            <van-field
              type="input"
              :clearable="true"
              v-model="put_user_name"
              placeholder="联系人姓名"
              v-if="addressType == '1'"
            ></van-field>
          </div>
        </div>
      </el-card>
      <div
        class="flex_cc"
        style="positon: absolute; width: 100%; padding: 10px 0; bottom: 0;left: 0;"
      >
        <el-button type="success" @click="confirmAddress()" round>确认</el-button>
      </div>
    </el-drawer>
    <el-drawer
      :with-header="false"
      :append-to-body="true"
      direction="btt"
      size="90%"
      :visible.sync="mapDrawer"
      custom-class="el-drawer"
    >
      <div class="amap-wrapper">
        <div class="search" style="padding: 10px;background-color: #eee;">
          <van-field
            id="input"
            @input="changeInputAddress()"
            v-model="inputAddress"
            placeholder="输入地址搜索"
            clearable
          ></van-field>
        </div>
        <div id="container" class="map" tabindex="0" style="height: 300px"></div>
        <van-list class="tipAddressList">
          <van-cell
            v-for="(item, index) in tipAddress"
            :key="index"
            :title="item.name"
            @click="chooseTipAddress(item.location, item.name)"
          />
        </van-list>
        <van-list>
          <van-cell
            v-for="(item, index) in poisAddress"
            :key="index"
            :title="item.name"
            @click="chooseTipAddress(item.location, item.name)"
          />
        </van-list>
      </div>
    </el-drawer>
    <!--   优惠券列表   -->
    <el-drawer
      :with-header="false"
      :append-to-body="true"
      direction="btt"
      size="50%"
      :visible.sync="couponsDrawer"
    >
      <div class="flex_cc buttonBox" style="padding: 10px;">
        <!-- <el-button type="info" @click="goodsDetailDialogCancel()">取消</el-button> -->
        <div class="flex_1 title" style="text-align: center;">选择优惠券</div>
        <el-button type="success" @click="chooseCouponsConfirm()">确定</el-button>
      </div>
      <van-list>
        <van-radio-group
          v-model="choose_coupon_list"
          direction="horizontal"
          @change="chooseCoupons()"
        >
          <van-cell-group style="width: 100%;">
            <van-cell>
              <template>
                <van-radio name="null" checked-color="#ff0000">
                  <div class="flex_" style="justify-content: space-between;min-width: 300px;">不使用优惠券</div>
                </van-radio>
              </template>
            </van-cell>
            <van-cell v-for="(item, index) in coupon_list" :key="index">
              <template v-if="buyKeepPrice" #right-icon>
                <van-radio
                  :name="index"
                  checked-color="#ff0000"
                  :disabled="firstTotalPrice + keepPriceNumber < parseInt(item.min_amount)"
                >
                  <div class="flex_" style="justify-content: space-between;min-width: 300px;">
                    <div>{{ item.name }}</div>
                    <div>最低消费：{{ item.min_amount }}</div>
                  </div>
                  <div class="flex_" style="justify-content: space-between;">
                    <div>{{ item.code }}</div>
                    <div
                      v-if="firstTotalPrice + keepPriceNumber < parseInt(item.min_amount)"
                    >未达到消费标准</div>
                  </div>
                </van-radio>
              </template>
              <template v-else #right-icon>
                <van-radio
                  :name="index"
                  checked-color="#ff0000"
                  :disabled="firstTotalPrice < parseInt(item.min_amount)"
                >
                  <div class="flex_" style="justify-content: space-between;min-width: 300px;">
                    <div>{{ item.name }}</div>
                    <div>最低消费：{{ item.min_amount }}</div>
                  </div>
                  <div class="flex_" style="justify-content: space-between;">
                    <div>{{ item.code }}</div>
                    <div v-if="firstTotalPrice < parseInt(item.min_amount)">未达到消费标准</div>
                  </div>
                </van-radio>
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </van-list>
    </el-drawer>
    <van-popup
      v-model="payOrder"
      round
      :close-on-click-overlay="false"
      closeable
      class="pay-order-popup"
    >
      <div class="flex_cc pay-order-box">
        <div class="title">付款详情</div>
        <div class="tips">需支付金额</div>
        <div class="total-money">{{ finalTotalPrice }}元</div>
        <van-button class="button" type="primary" @click="callpay()">立即支付</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import axios from "axios";

export default {
  props: {
    user: Object,
    start_price: String,
    coupon_list: Array,
    // 物品类型
    gives: Array
  },
  data() {
    return {
      // 订单类型
      orderType: 1,
      // 图标
      icon: {
        send: require("../../static/icon_send1.png"),
        get: require("../../static/icon_get1.png"),
        goods: require("../../static/icon_goods.png"),
        time: require("../../static/icon_time.png"),
        coupon: require("../../static/icon_coupon.png"),
        note: require("../../static/icon_note.png"),
        heat: require("../../static/icon_heat.png")
      },
      // 保温箱
      heat: false,
      coupon: "2",
      // 初始计算总价
      firstTotalPrice: 0,
      // 最终总价（实际支付金额）
      finalTotalPrice: 0,
      // 骑行时间
      totalTime: "",
      // 距离
      distance: "",
      // 物品类型弹窗
      goodsDialog: false,
      // 物品类型表单
      form: {
        radio1: "null",
        radio2: "null"
      },
      // 物品价值
      goodsPrice: [
        { id: 0, name: "0 ~ 500" },
        { id: 1, name: "500 ~ 10000" }
      ],
      // 投保价格
      keepPriceNumber: 0,
      // 是否投保
      buyKeepPrice: false,
      // 保价协议
      keepPrice: true,
      confirmGoods: "请选择物品规格",
      // 时间选择
      dataTime: [
        {
          text: "今天",
          children: [
            {
              text: "立即发货",
              children: [{ text: "" }]
            }
          ]
        },
        {
          text: "明天",
          children: []
        }
      ],
      datetimeDialog: false,
      confirmTime: "立即发货",
      orderDetailDialog: false,
      orderDetail: "",
      // 选择优惠券 index
      choose_coupon_list: "null",
      // 选择优惠券最低消费
      choose_coupon_list_price: 0,
      // 选择优惠券 优惠价格
      choose_coupon_discount_price: 0,
      // 是否优惠券可选
      couponsDisabled: false,
      // 地址类型
      addressType: "0",
      // 定位地址
      position_address: {
        name: ""
      },
      // 发货地址
      send_address: {},
      send_detail_address: "",
      send_user_tel: this.user.phone,
      send_user_name: "",
      // 收获地址
      put_address: {},
      put_detail_address: "",
      put_user_tel: "",
      put_user_name: "",
      // 高德地图
      inputAddress: "",
      tipAddress: [],
      poisAddress: [],
      addressDrawer: false,
      mapDrawer: false,
      couponsDrawer: false,
      // 提交订单数据
      submitData: {},
      //  唤起支付
      payOrder: false,
      config: String,
      order_no: String
    };
  },
  mounted() {
    this.getGeolocation();
    console.log(this.coupon_list)
  },
  methods: {
    // 物品规格
    openGoodsDialog() {
      if (!this.position_address.name && !this.send_address.name) {
        this.$toast("请选择发货地址");
        return false;
      } else if (!this.put_address.name) {
        this.$toast("请选择收货地址");
        return false;
      }
      this.goodsDialog = true;
    },
    // 物品价值
    chooseGoodsPrice() {
      if (this.form.radio2 === 0) {
        this.keepPriceNumber = 3;
        this.buyKeepPrice = false;
      } else if (this.form.radio2 === 1) {
        this.keepPriceNumber = 5;
        this.buyKeepPrice = true;
        this.$toast("贵重物品建议选择投保");
      }
    },
    // 选择投保
    cancelBuyKeepPrice() {
      if (this.buyKeepPrice && this.keepPriceNumber === 5) {
        this.$toast("贵重物品建议选择投保");
      } else if (!this.buyKeepPrice && this.keepPriceNumber === 5) {
        this.$toast("选择不投保，若有损失，平台最多赔付三倍跑腿费");
      }
    },
    // 确认物品类型
    goodsDialogConfirm() {
      if (this.form.radio1 === "null") {
        this.$toast("请选择物品类型");
        return false;
      }
      if (this.form.radio2 === "null") {
        this.$toast("请选择物品价值");
        return false;
      }

      // 物品类型
      this.submitData.give_id = this.form.radio1;

      // 页面显示
      this.confirmGoods =
        this.gives[this.form.radio1].name +
        " " +
        this.goodsPrice[this.form.radio2].name;
      this.goodsDialog = false;

      /**
       * 计算价格
       */
      // 选择保价
      if (this.buyKeepPrice) {
        // 达到最低消费
        if (
          this.firstTotalPrice + this.keepPriceNumber >=
          this.choose_coupon_list_price
        ) {
          // 使用优惠券后，支付金额 大于 0
          if (
            this.firstTotalPrice + this.keepPriceNumber >
            this.choose_coupon_discount_price
          ){
            // 最终总价 = 初始计算总价 + 保价金额 - 优惠券金额
            this.finalTotalPrice = this.firstTotalPrice + this.keepPriceNumber - this.choose_coupon_discount_price;
          // 使用优惠券后，支付金额 小于等于 0
          }else{
            this.finalTotalPrice = 0.01;
          }
        // 未达到最低消费
        } else {
          // 之前已经选择优惠券
          if (this.choose_coupon_list !== "null"){
            // 取消选择优惠券
            this.choose_coupon_list = "null"
            this.choose_coupon_list_price = 0;
            this.choose_coupon_discount_price = 0;
            this.$toast("未达到最低消费，自动取消已选择的优惠券")
          }
          // 最终总价 = 初始计算总价 + 保价金额
          this.finalTotalPrice = this.firstTotalPrice + this.keepPriceNumber;
        }
      // 不保价
      } else {
        // 达到优惠券最低消费
        if (this.firstTotalPrice >= this.choose_coupon_list_price) {
          // 使用优惠券后，支付金额 大于 0
          if ( this.firstTotalPrice > this.choose_coupon_discount_price ){
            // 最终总价 = 初始计算总价 - 优惠券金额
            this.finalTotalPrice = this.firstTotalPrice - this.choose_coupon_discount_price;
          // 使用优惠券后，支付金额 小于等于 0
          }else{
            this.finalTotalPrice = 0.01;
          }
        // 未达到最低消费
        } else {
          // 之前已经选择优惠券
          if (this.choose_coupon_list !== "null"){
            // 取消选择优惠券
            this.choose_coupon_list = "null"
            this.choose_coupon_list_price = 0;
            this.choose_coupon_discount_price = 0;
            this.$toast("未达到最低消费，自动取消已选择的优惠券")
          }
          // 最终总价 = 初始计算总价
          this.finalTotalPrice = this.firstTotalPrice;
        }
      }
    },
    // 选择时间
    clickChooseTime() {
      this.datetimeDialog
        ? (this.datetimeDialog = false)
        : (this.datetimeDialog = true);
      let hour = new Date().getHours();
      let todayHour = [];
      for (let i = hour + 1; i < 24; i++) {
        i < 10 ? (i = "0" + i) : i;
        this.dataTime[0].children.push({
          text: i + "时",
          children: [
            { text: "00分" },
            { text: "10分" },
            { text: "20分" },
            { text: "30分" },
            { text: "40分" },
            { text: "50分" }
          ]
        });
      }
      let tomorrowHour = [];
      for (let i = 1; i < 24; i++) {
        i < 10 ? (i = "0" + i) : i;
        this.dataTime[1].children.push({
          text: i + "时",
          children: [
            { text: "00分" },
            { text: "10分" },
            { text: "20分" },
            { text: "30分" },
            { text: "40分" },
            { text: "50分" }
          ]
        });
      }
    },
    // 取消选择时间
    pickerCancel() {
      this.datetimeDialog = false;
    },
    // 确认选择时间
    pickerConfirm(value) {
      this.datetimeDialog = false;
      // 给用户看的时间
      this.confirmTime = value.join(" ");
      // 获取时间
      let year = new Date().getFullYear();
      let month = new Date().getMonth() + 1;
      month < 10 ? (month = "0" + month) : month;
      let date = new Date().getDate();
      date < 10 ? (date = "0" + date) : date;
      let tomorrowDate = new Date().getDate() + 1;
      tomorrowDate < 10 ? (tomorrowDate = "0" + tomorrowDate) : tomorrowDate;
      let hour = new Date().getHours();
      let minute = new Date().getMinutes();
      let second = ":00";

      let delivery_time = "";
      if (value[0] === "今天") {
        delivery_time = delivery_time + year + "-" + month + "-" + date;
        if (value[1] === "立即发货") {
          delivery_time = "";
        } else {
          delivery_time =
            delivery_time +
            " " +
            value[1].substring(0, 2) +
            ":" +
            value[2].substring(0, 2) +
            second;
        }
      } else if (value[0] === "明天") {
        delivery_time =
          delivery_time +
          year +
          "-" +
          month +
          "-" +
          tomorrowDate +
          " " +
          value[1].substring(0, 2) +
          ":" +
          value[2].substring(0, 2) +
          second;
      } else {
        console.log("时间错误");
      }
      // 发货时间
      this.submitData.delivery_time = delivery_time;
    },
    // 订单备注
    openOrderDetailDialog() {
      this.orderDetailDialog = true;
    },
    goodsDetailDialogConfirm() {
      this.orderDetailDialog = false;
    },
    // 打开地址页
    openAddressDrawer(addressType) {
      this.addressType = addressType;
      this.addressDrawer = true;
    },
    //  定位
    getGeolocation() {
      let that = this;
      // 加载定位插件，实现定位功能
      AMap.plugin("AMap.Geolocation", function() {
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：无穷大
          maximumAge: 0, //定位结果缓存0毫秒，默认：0
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野s内可见，默认：false
        });
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete); //返回定位信息
        AMap.event.addListener(geolocation, "error", onError); //返回定位出错信息
        function onComplete(data) {
          // data是具体的定位信息
          console.log(data);
          that.position_address.position = [
            data.position.lng,
            data.position.lat
          ];
          that.doRegeoCode();
        }
        function onError(data) {
          // 定位出错
          console.log(data);
        }
      });
    },
    // 地理位置逆向
    doRegeoCode() {
      let that = this;
      let geocoder = new AMap.Geocoder({
        city: "0561", //城市设为北京，默认：“全国”
        radius: 1000 //范围，默认：500
      });
      let lnglat = this.position_address.position;
      geocoder.getAddress(lnglat, function(status, result) {
        if (status === "complete" && result.regeocode) {
          let address = result.regeocode.formattedAddress;
          address = address.substring(6, address.length);
          that.position_address.name = address;
        } else {
          log.error("根据经纬度查询地址失败");
        }
      });
    },
    // 高德地图
    positionPicker() {
      let that = this;
      //拖拽地址
      AMapUI.loadUI(["misc/PositionPicker"], function(PositionPicker) {
        var map = new AMap.Map("container", {
          zoom: 16,
          scrollWheel: false
        });
        var positionPicker = new PositionPicker({
          mode: "dragMap",
          map: map,
          iconStyle: {
            //自定义外观
            url: "//webapi.amap.com/ui/1.0/assets/position-picker2.png", //图片地址
            size: [48, 48], //要显示的点大小，将缩放图片
            ancher: [24, 40] //锚点的位置，即被size缩放之后，图片的什么位置作为选中的位置
          }
        });
        // 加载定位插件，实现定位功能
        AMap.plugin("AMap.Geolocation", function() {
          let geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 10000, //超过10秒后停止定位，默认：无穷大
            maximumAge: 0, //定位结果缓存0毫秒，默认：0
            showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野s内可见，默认：false
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition();
          AMap.event.addListener(geolocation, "complete", onComplete); //返回定位信息
          AMap.event.addListener(geolocation, "error", onError); //返回定位出错信息
          function onComplete(data) {
            // data是具体的定位信息
            console.log(data);
          }
          function onError(data) {
            // 定位出错
            console.log(data);
          }
        });
        positionPicker.on("success", function(positionResult) {
          that.poisAddress = positionResult.regeocode.pois.slice(0, 10);
        });
        positionPicker.on("fail", function(positionResult) {
          console.log(positionResult);
        });
        var onModeChange = function(e) {
          positionPicker.setMode(e.target.value);
        };
        positionPicker.start();
      });
    },
    // 确认地址
    confirmAddress() {
      if (this.put_address.name) {
        if (this.position_address.name !== "" || this.send_address.name) {
          this.countPrice();
        } else {
          this.$toast("请选择发货地址");
        }
      }
      this.addressDrawer = false;
    },
    // 打开拖拽选址
    openMapDrawer() {
      this.mapDrawer = true;
      this.positionPicker();
    },
    // 输入联想
    changeInputAddress() {
      let that = this;
      // 获取输入提示信息
      var keywords = this.inputAddress;
      AMap.plugin("AMap.Autocomplete", function() {
        // 实例化Autocomplete
        var autoOptions = {
          city: "淮北"
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(keywords, function(status, result) {
          that.tipAddress = result.tips;
        });
      });
    },
    // 选址联想地址
    chooseTipAddress(data, address) {
      if (this.addressType == "0") {
        this.send_address.name = address;
        this.send_address.lng = data.lng;
        this.send_address.lat = data.lat;
      } else {
        this.put_address.name = address;
        this.put_address.lng = data.lng;
        this.put_address.lat = data.lat;
      }
      this.mapDrawer = false;
    },
    // 打开优惠券选择
    openCouponsList() {
      if (!this.put_address.lat) {
        this.$toast("请先选择地址");
      } else if (this.form.radio1 === "null") {
        this.$toast("请先选择物品规格");
      } else {
        if (this.coupon_list.length === 0) {
          this.$toast("暂无可用的优惠券");
        } else {
          this.couponsDrawer = true;
          console.log(this.coupon_list);
        }
      }
    },
    // 选择优惠券
    chooseCoupons() {
      if (this.choose_coupon_list !== "null") {
        this.choose_coupon_list_price = parseInt(this.coupon_list[this.choose_coupon_list].min_amount);
        this.choose_coupon_discount_price = parseInt(this.coupon_list[this.choose_coupon_list].price);
      } else {
        this.choose_coupon_list_price = 0;
        this.choose_coupon_discount_price = 0;
      }
    },
    // 确认使用优惠券
    chooseCouponsConfirm() {
      if (this.choose_coupon_list !== "null") {
        this.submitData.coupon = this.coupon_list[this.choose_coupon_list].id;
        this.choose_coupon_name = this.coupon_list[this.choose_coupon_list].name;
      } else {
        this.submitData.coupon = "null";
        this.choose_coupon_name = "null";
      }
      /**
       * 计算金额
       * 由于只可以选择已达到消费标准的优惠券，
       * 所以不判断当前价格是否达到最低消费
       */
      // 选择保价
      if (this.buyKeepPrice) {
        // 使用优惠券后 支付金额大于0
        if (
          this.firstTotalPrice + this.keepPriceNumber >
          this.choose_coupon_discount_price
        ) {
          // 最终总价 = 初始计算总价 + 保价金额 - 优惠券金额
          this.finalTotalPrice =
            this.firstTotalPrice +
            this.keepPriceNumber -
            this.choose_coupon_discount_price;
        // 使用优惠券后 支付金额小于等于0
        } else {
          this.finalTotalPrice = 0.01;
        }
      // 不保价
      } else {
        // 使用优惠券后 支付金额大于0
        if (this.firstTotalPrice > this.choose_coupon_discount_price) {
          // 最终总价 = 初始计算总价 - 优惠券金额
          this.finalTotalPrice =
            this.firstTotalPrice - this.choose_coupon_discount_price;
        // 使用优惠券后 支付金额小于0
        } else {
          this.finalTotalPrice = 0.01;
        }
      }
      // 关闭优惠券弹窗
      this.couponsDrawer = false;
    },
    // 获取初始计算价格
    countPrice() {
      let that = this;
      let data = {};
      if (!this.send_address.name) {
        data = {
          send_longitude: this.position_address.position[0],
          send_latitude: this.position_address.position[1],
          put_longitude: this.put_address.lng,
          put_latitude: this.put_address.lat
        };
      } else {
        data = {
          send_longitude: this.send_address.lng,
          send_latitude: this.send_address.lat,
          put_longitude: this.put_address.lng,
          put_latitude: this.put_address.lat
        };
      }
      axios
        .get("/home/api/getPrice", {
          params: data
        })
        .then(res => {
          if (res.status === 200) {
            this.$toast("计算成功");
            that.firstTotalPrice = res.data.total_price.toFixed(2);
            that.totalTime = res.data.total_time;
            that.distance = res.data.distance;

            /**
             * 计算价格
             */
            // 选择保价
            if (this.buyKeepPrice) {
              // 达到最低消费
              if (
                this.firstTotalPrice + this.keepPriceNumber >=
                this.choose_coupon_list_price
              ) {
                // 使用优惠券后，支付金额 大于 0
                if (
                  this.firstTotalPrice + this.keepPriceNumber >
                  this.choose_coupon_discount_price
                ){
                  // 最终总价 = 初始计算总价 + 保价金额 - 优惠券金额
                  this.finalTotalPrice = this.firstTotalPrice + this.keepPriceNumber - this.choose_coupon_discount_price;
                // 使用优惠券后，支付金额 小于 0
                }else{
                  this.finalTotalPrice = 0.01;
                }
              // 未达到最低消费
              } else {
                // 之前已经选择优惠券
                if (this.choose_coupon_list !== "null"){
                  // 取消选择优惠券
                  this.choose_coupon_list = "null"
                  this.choose_coupon_list_price = 0;
                  this.choose_coupon_discount_price = 0;
                  this.$toast("未达到最低消费，自动取消已选择的优惠券")
                }
                // 最终总价 = 初始计算总价 + 保价金额
                this.finalTotalPrice = this.firstTotalPrice + this.keepPriceNumber;
              }
            // 不保价
            } else {
              // 达到优惠券最低消费
              if (this.firstTotalPrice >= this.choose_coupon_list_price) {
                // 使用优惠券后，支付金额 大于 0
                if ( this.firstTotalPrice > this.choose_coupon_discount_price ){
                  // 最终总价 = 初始计算总价 - 优惠券金额
                  this.finalTotalPrice = this.firstTotalPrice - this.choose_coupon_discount_price;
                // 使用优惠券后，支付金额 小于等于 0
                }else{
                  this.finalTotalPrice = 0.01;
                }
              // 未达到最低消费
              } else {
                // 之前已经选择优惠券
                if (this.choose_coupon_list !== "null"){
                  // 取消选择优惠券
                  this.choose_coupon_list = "null"
                  this.choose_coupon_list_price = 0;
                  this.choose_coupon_discount_price = 0;
                  this.$toast("未达到最低消费，自动取消已选择的优惠券")
                }
                // 最终总价 = 初始计算总价
                this.finalTotalPrice = this.firstTotalPrice;
              }
            }

            // 过近距离提示
            if (parseInt(res.data.distance) < 1){
              that.$toast("配送距离少于一公里，请确认地址无误。")
            }
          } else {
            console.log("错误");
          }
        })
        .catch(res => {
          console.log(res);
        });
    },
    // 提交订单
    submit() {
      // 订单类型
      this.submitData.type = this.orderType;
      // 地址发货
      this.submitData.send_address = this.send_address.name;
      this.submitData.send_longitude = this.send_address.lng;
      this.submitData.send_latitude = this.send_address.lat;
      this.submitData.send_detail_address = this.send_detail_address;
      // 地址收货
      this.submitData.put_address = this.put_address.name;
      this.submitData.put_longitude = this.put_address.lng;
      this.submitData.put_latitude = this.put_address.lat;
      this.submitData.put_detail_address = this.put_detail_address;
      // 联系方式
      this.submitData.send_user_tel = this.send_user_tel;
      this.submitData.put_user_tel = this.put_user_tel;
      // 联系人
      this.submitData.send_user_name = this.send_user_name;
      this.submitData.put_user_name = this.put_user_name;
      // 物品类型（已选择）
      //  是否保价
      if (this.buyKeepPrice) {
        this.submitData.is_insurance = 1;
      } else {
        this.submitData.is_insurance = 0;
      }
      // 保价金额
      this.submitData.insurance_price = this.keepPriceNumber;
      // 发货时间
      if (this.confirmTime === "立即发货") {
        this.submitData.delivery_time = "null";
      } else {
        // 发货时间（格式已改）
      }
      // 优惠券（id 已选择）
      // 保温箱
      if (this.heat) {
        this.submitData.warm = 1;
      } else {
        this.submitData.warm = 0;
      }
      // 订单备注
      this.submitData.remark = this.orderDetail;
      // 订单总价（使用优惠券后）
      this.submitData.total_amount = this.finalTotalPrice;
      // 订单原价（不使用优惠券）
      if (this.buyKeepPrice) {
        this.submitData.original_price =
          this.firstTotalPrice + this.keepPriceNumber;
      } else {
        this.submitData.original_price = this.firstTotalPrice;
      }

      // 提交订单，（请求支付参数，不生成订单）
      let submitData = this.submitData;
      axios
        .post("pay", submitData)
        .then(res => {
          console.log(res);
          if (res.status === 200) {
            // this.$toast(res.data.msg);
            this.payOrder = true;
            this.config = JSON.parse(res.data.config);
            this.order_no = res.data.order_no;
            console.log(this.config);
          }
        })
        .catch(err => {
          if (err.response.data.hasOwnProperty("errors")) {
            console.log(err.response);
            let obj = err.response.data.errors;
            for (let key in obj) {
              for (let key2 in obj[key]) {
                this.$toast(obj[key][0]);
                return false;
              }
              return false;
            }
          } else {
            this.$toast(err.response.data.msg);
            return false;
          }
        });
    },
    // 微信接口，唤起支付
    callpay() {
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
        } else if (document.attachEvent) {
          document.attachEvent("WeixinJSBridgeReady", jsApiCall);
          document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
        }
      } else {
        this.jsApiCall();
        this.orderPay();
      }
    },
    // 微信支付
    jsApiCall() {
      WeixinJSBridge.invoke("getBrandWCPayRequest", this.config, function(res) {
        // 微信接口判断
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          // 支付成功
          alert("支付成功");
          setTimeout(function() {
            window.location.href = "/home/index"; //你想跳转的页面
          }, 1000);
        }
        if (res.err_msg == "get_brand_wcpay_request:fail") {
          // 支付失败
          alert("支付失败");
          setTimeout(function() {
            window.location.href = "/home/index"; //你想跳转的页面
          }, 1000);
        }
        if (res.err_msg == "get_brand_wcpay_request:cancel") {
          // 取消支付
          alert("取消支付");
          setTimeout(function() {
            window.location.href = "/home/index"; //你想跳转的页面
          }, 1000);
        }
      });
    },
    // 微信支付窗口确认支付时提交订单
    orderPay() {
      // 关闭预支付弹窗
      this.payOrder = false;
      // 再次提交订单，（此次生成订单）
      let submitData = this.submitData;
      submitData.order_no = this.order_no;
      submitData.config = this.config;
      console.log(this.submitData)
      axios
        .post("user/bind", submitData) // 接口改成生成订单 的地址
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>
